import FBook from "./FBook";
import Bezier from 'bezier';

var GameData = require('../module/gameData')();
var fishfactory = require('../module/fishfactory')();
var that;
cc.Class({
    extends: cc.Component,

    properties: {
        coinNum: cc.Label,
        coin1: cc.Prefab,
        coin2: cc.Prefab,
        coin3: cc.Prefab,
        Layer: cc.Node,
        l1: cc.Label,
        l2: cc.Label,
        openShow: false,
        fishprefab: {
            default: [],
            type: cc.Prefab
        },
        header: cc.Node,
        addcoin: cc.Prefab,

        qipao: cc.Prefab,
        qipaoli: cc.ParticleSystem,

        rankNum: cc.Label,

        moveMusic: {
            default: [],
            type: [cc.AudioClip]
        },
        // Allfishprefab: cc.Prefab, /* 各种鱼的纹理集 */
    },
    // LIFE-CYCLE CALLBACKS:
    onLoad() {
        GameData.gameHome = this;
        this.openShow = false;
        that = this;
        GameData.gameUpgrade = 0;
        this.homeFish = [];
        that.loaded = false;

        this.loadheader();
        this.addqipao();
        // this.createNewFish(1);
        this.coinArray = [];
        this.getOnlineTime();

        this.fishData = GameData.getlocalData("fishData");
        console.log(this.fishData);

        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouch, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouch, this);
        this.headUrl = null;
        var Arr = this.fishData.coinArr.concat();
        for (var a = 0; a < Arr.length; a++) {
            this.createCoin(Arr[a].type, Arr[a].x, Arr[a].y, false);
        }
        var id = GameData.playMusic(this.moveMusic[0], true);
        cc.audioEngine.setVolume(id, 0.3);
        // var backfun = function (myIndex) {
        //     if (myIndex >= 0) {
        //     } else {
        //         myIndex = 0
        //     }
        //     that.rankNum.string = myIndex + ""
        // };
        // FBook.getInfoType("getMySelfRankInfoForFaceBook", backfun);

        setTimeout(function () {
            cc.director.preloadScene("game", function () {
            });
            cc.director.preloadScene("upgrade", function () {
            });
        }, 500)
    },
    onTouch(evt) {
        switch (evt.type) {
            case "touchstart":
                this.check_isget(evt.getLocation());
                break;
            case "touchmove":
                this.check_isget(evt.getLocation());
                break;
            case "touchend":

                break;
            case "touchcancel":

                break;
        }
    },
    check_isget(pos) {
        var pos2 = this.node.convertToNodeSpaceAR(pos);
        for (var a = 0; a < this.coinArray.length; a++) {
            var pos11 = this.coinArray[a].parent.convertToWorldSpaceAR(this.coinArray[a].getPosition());
            var _pos1 = this.node.convertToNodeSpaceAR(pos11);
            var _d = this.getDistance(pos2, _pos1);
            if (_d <= 50) {
                this.fishData = GameData.getlocalData("fishData");
                var num=this.fishData.coinNum+this.coinArray[a].price;
                this.fishData.coinNum=num
                console.log(num,this.fishData.coinNum);

                this.coinArray[a].getComponent("coin").init();
                this.addcoinAct(this.coinArray[a].x, this.coinArray[a].y, this.coinArray[a].price);
                for (var i = 0; i < this.fishData.coinArr.length; i++) {
                    var _obj = this.fishData.coinArr[i];
                    if (_obj.type == this.coinArray[a].type && _obj.x == this.coinArray[a].x && _obj.y == this.coinArray[a].y) {
                        this.fishData.coinArr.splice(i, 1);
                        GameData.savelocalData(this.fishData);
                        this.fishData = GameData.getlocalData("fishData");
                        console.log("ssss", this.fishData);
                        i--
                        break;
                    }
                }
                this.coinArray.splice(a, 1);
                a--;
            }
        }
    },

    /*获取两点间的距离*/
    getDistance(pos1, pos2) {
        return Math.sqrt(Math.pow((pos1.x - pos2.x), 2) + Math.pow((pos1.y - pos2.y), 2));
    },
    onEnable() {

        this.fishData = GameData.getlocalData("fishData");
        GameData.enter();
        GameData.isPause = false;
        for (var a = 0; a < this.fishData.handbook.oldfish.length; a++) {
            if (typeof(this.fishData.handbook.oldfish[a]) == 'number') {
                this.createFish(this.fishData.handbook.oldfish[a]);
            } else {
                this.fishData.handbook.oldfish.splice(a, 1);
                a--
            }
        }
        for (var a = 0; a < this.homeFish.length; a++) {
            if (this.homeFish[a].id != 12 && this.homeFish[a].id != 13 && this.homeFish[a].id != 14) {
                var _len = GameData.moveData[this.homeFish[a].moveid].length;
                this.homeFish[a].movidx = Math.floor(Math.random() * _len);
                let bezier1 = GameData.moveData[this.homeFish[a].moveid][this.homeFish[a].movidx];
                this.homeFish[a].moveArr = Bezier(bezier1, 100, this.homeFish[a].time);
            }
        }
        /*展示晚间金币数*/
        this.coinNum.string = this.fishData.coinNum + "";
        /*初始化鱼缸的显示信息*/
        this.initPaenlText();
        /*是否有新鱼 如果有新鱼则打开面板*/
        this.openShowpanel();
    },

    /*
      * desc  :在线收益 和  离线收益
      * author:<zhouzhiwei>
      * @param:
      * date  : 2018/12/25
    */
    getOnlineTime() {
        this.fishData = GameData.getlocalData("fishData");
        var num = this.fishData.handbook.oldfish.length;
        var _Arr1 = [
            {min: 1, max: 5, _t: 80},
            {min: 6, max: 11, _t: 60},
            {min: 12, max: 17, _t: 50},
        ];
        this._t = 0;
        var coinMax;
        /*获取相对应的时间间隔*/
        for (var a = 0; a < _Arr1.length; a++) {
            if (num >= _Arr1[a].min && num <= _Arr1[a].max) {
                this._t = _Arr1[a]._t;
            }
        }
        ;
        /*获取每天最大离线收益*/
        for (var a = 0; a < GameData.upgradeData.lixian.length; a++) {
            if (num == GameData.upgradeData.lixian[a].num) {
                coinMax = GameData.upgradeData.lixian[a].money;
                break;
            }
        }
        if (GameData.playTime <= 0) {
            var coinnum;
            if (num > 0) {
                var date1 = this.fishData.saveTime;  //开始时间
                var date2 = new Date();    //结束时间
                var date3 = date2.getTime() - new Date(date1).getTime();   //时间差的毫秒数
                if (parseInt(date3 / 1000) > 5 * 60) {
                    var date4 = parseInt(date3 / 1000) - 5 * 60;
                    /*通过上次保存数据的时间与当前时间的差 减去如果5分钟不保存数据的时间 则表示5分钟之后的时间算是离线时间*/
                    coinnum = parseInt(date4 / this._t);
                    /*计算出离线所得的金币数*/
                    if (coinnum > coinMax) {
                        coinnum = coinMax
                    }
                    this.getCoin(coinnum);
                } else {
                    // console.log("时间太短，没有达到离线条件")
                }
            }
        } else {
            coinnum = parseInt(GameData.playTime / this._t);
            if (coinnum > 0) {
                for (var a = 0; a < coinnum; a++) {
                    var type = Math.floor(Math.random() * 3);
                    this.addcoinfun(1, type);
                }
                // console.log("在线时长", parseInt(GameData.playTime), "达到的时间条件", this._t, "创建了随机道具", coinnum, "个")
            } else {
                // console.log("在线时长太短", parseInt(GameData.playTime), "达到的时间条件", this._t)
            }
            GameData.playTime = 0;
            this.iscount = true;
        }
    },
    /*load加载头像*/
    loadheader() {
        if (this.headUrl) {
            var container = this.header.getComponent(cc.Sprite);//图片呈现位置
            cc.loader.load(playerPic, function (err, texture) {
                var sprite = new cc.SpriteFrame(texture);
                container.spriteFrame = sprite;
                that.header.width = 100;
                /*防止从facebook上下载下来的图片大于或者小于100*100 尺寸的图片*/
                that.header.height = 100;
            });
        } else {
            var that = this;
            var backfun = function (playerPic) {
                var container = that.header.getComponent(cc.Sprite);//图片呈现位置
                // console.log("loadheader", playerPic);
                if (playerPic) {
                    /*加载远程资源*/
                    cc.loader.load(playerPic, function (err, texture) {
                        var sprite = new cc.SpriteFrame(texture);
                        container.spriteFrame = sprite;
                        that.header.width = 100;
                        /*防止从facebook上下载下来的图片大于或者小于100*100 尺寸的图片*/
                        that.header.height = 100;
                    });
                } else {
                    playerPic = 'header.jpg';
                    cc.loader.loadRes(playerPic, function (err, texture) {
                        var sprite = new cc.SpriteFrame(texture);
                        container.spriteFrame = sprite;
                    });
                }
            }
            FBook.getInfoType("getPhoto", backfun);
        }

        // var playerPic = "https://fs-uc-nearme-com-cn.oss-cn-hangzhou.aliyuncs.com/946/882/383/383288649.jpg";

    },
    createFish(id) {
        var _x = Math.floor(Math.random() * 1130 - 565);
        fishfactory.createfish(id, _x, 500, that.fishprefab, this.Layer, this.homeFish, null, 1);
    },
    anginMove(sp) {
        var bezierid = fishfactory.getbezierid(this.homeFish);
        sp.moveStop = false;
        sp.runTime = 0;
        sp.movidx = 0
        // sp.getChildByName("Allfish").getChildByName("fishtype").getChildByName("fish").getComponent("fishmove").getMovePath(this.node.parent, "bezier_id_" + bezierid);
    },
    /*
      * desc  :创建新鱼
      * author:<zhouzhiwei>
      * @param:
      * date  : 2018/12/25
    */
    createNewFish(id) {
        var _x = Math.floor(Math.random() * 1130 - 565);
        // var bezierid = Math.floor(Math.random() * 2 + 40);
        var bezierid = 40;
        var _fish = fishfactory.createfish(id, _x, 500, that.fishprefab, this.Layer, this.homeFish, null, 1, bezierid);
        _fish.moveStop = true;
        var _moveid = "bezier_id_" + bezierid;
        var endpos = GameData.moveData[_moveid][0][0];
        _fish.x = endpos.x;
        _fish.y = 360;
        _fish.getChildByName("Allfish").rotation = -90;
        _fish.getChildByName("Allfish").scaleY = -1;
        this.qipaoli.node.runAction(
            cc.sequence(
                cc.callFunc(function () {
                    that.qipaoli.resetSystem();
                }),
                cc.moveTo(0.8, endpos.x, endpos.y).easing(cc.easeOut(1)),
                cc.callFunc(function () {
                    that.qipaoli.stopSystem();
                    that.qipaoli.node.active = false;
                })
            )
        );
        _fish.runAction(cc.sequence(
            cc.moveTo(0.8, endpos.x, endpos.y).easing(cc.easeIn(1)),
            cc.callFunc(function () {
                _fish.moveStop = false;
            })
        ));
        this.openShow = true;
    },
    /*
    * desc: 根据是否有新鱼打开面板
    * author: <zhouzhiwei>
    * @param:
    * date: 2018/12/15
    */
    openShowpanel() {
        this.fishData = GameData.getlocalData("fishData");
        let _Arr = this.fishData.handbook.newfish;
        if (_Arr.length > 0) {
            this.openShow = false;

            this.initPaenlText();
            cc.find("panel").active = true;
        } else {
            this.openShow = false;
            cc.find("panel").active = false;
        }
        this.initPaenlText()
    },
    /*
    * desc: 初始化面板上的文字
    * author: <zhouzhiwei>
    * @param:
    * date: 2018/12/15
    */
    initPaenlText() {
        this.fishData = GameData.getlocalData("fishData");
        var _num2 = GameData.upgradeData.box[this.fishData.upgrade.box - 1].Allnum;
        this.l2.string = _num2 + "";
        var _num1 = this.fishData.handbook.oldfish.length;
        this.l1.string = _num1 + "";
    },
    /*
    * desc: 计算离线时鱼产生多少金币 银币  宝石
    * author: <zhouzhiwei>
    * @param:
    * date: 2018/12/15
    */
    getCoin(Allcoin) {
        var baoshiNum = parseInt(Allcoin * 0.8 / 500);
        var coinNum = parseInt(0.8 * (Allcoin - baoshiNum * 500) / 50);
        var yinbiNum = (Allcoin - coinNum * 50) / 10;
        this.addcoinfun(baoshiNum, 2);
        this.addcoinfun(coinNum, 1);
        this.addcoinfun(yinbiNum, 0);
        // console.log("离线收益", Allcoin, "宝石：", baoshiNum, "金币", coinNum, "银币", yinbiNum);
    },
    /*
    * desc:  根据数量创建某种类型的鱼
    * author: <zhouzhiwei>
    * @param:
    * date: 2018/12/15
    */
    addcoinfun(num, type) {
        for (var a = 0; a < num; a++) {
            this.initCoin(type);
        }
    },
    initCoin(type) {
        /*x-556 -400   y:-117 -20*/
        var Arr_xAll = [];
        var Arr_x = [];
        var Arr_yAll = [];
        var Arr_y = [];
        for (var a = -518; a < 519; a++) {
            if (a >= -350 || a < -506) {
                Arr_x.push(a);
            }
            Arr_xAll.push(a);

        }
        for (var a = -145; a < 182; a++) {
            if (a >= 30 || a < -167) {
                Arr_y.push(a);
            }
            Arr_yAll.push(a);
        }
        var num = Math.floor(Math.random() * 2);
        var _x, _y;
        if (num == 1) {
            var idx1, idx2;
            idx1 = Math.floor(Math.random() * Arr_x.length);
            _x = Arr_x[idx1];
            idx2 = Math.floor(Math.random() * Arr_yAll.length);
            _y = Arr_yAll[idx2];
        } else {
            var idx1, idx2;
            idx1 = Math.floor(Math.random() * Arr_xAll.length);
            _x = Arr_xAll[idx1];
            idx2 = Math.floor(Math.random() * Arr_y.length);
            _y = Arr_y[idx2];
        }
        this.createCoin(type, _x, _y, true);
    },
    /*
    * desc: 根据类型创建鱼
    * author: <zhouzhiwei>
    * @param:
    * date: 2018/12/15
    */
    createCoin(type, _x, _y, _bool) {

        var _Arr = [this.coin1, this.coin2, this.coin3];
        var obj = _Arr[type];
        var _coin = cc.instantiate(obj);
        _coin.parent = this.Layer;
        _coin.x = _x;
        _coin.y = _y;
        _coin.type = type;
        _coin.id = this.coinArray.length;
        var price;
        switch (type) {
            case 0:
                price = 10;
                break;
            case 1:
                price = 50;
                break;
            case 2:
                price = 500;
                break;
        }
        ;
        _coin.price = price;
        var obj = {
            type: type,
            x: _x,
            y: _y,
        }
        if (_bool) {
            this.fishData.coinArr.push(obj);
            GameData.savelocalData(this.fishData);
        }
        if (this.coinArray.length > 20) {
            for (var i = 0; i < this.fishData.coinArr.length; i++) {
                var _obj = this.fishData.coinArr[i];
                if (_obj.type == this.coinArray[0].type && _obj.x == this.coinArray[0].x && _obj.y == this.coinArray[0].y) {
                    this.fishData.coinArr.splice(i, 1);
                    break;
                }
            }
            GameData.savelocalData(this.fishData);
            this.coinArray[0].getComponent("coin").init();
            this.addcoinAct(this.coinArray[0].x, this.coinArray[0].y, this.coinArray[0].price);
            this.coinArray.splice(0, 1);
        }
        this.coinArray.push(_coin);
    },
    selectBtn(evt) {
        let _name = evt.currentTarget.name;
        console.log("zzw",this.fishData);
        cc.find("loading").active = true;
        switch (_name) {
            case "music":/* 弹出音乐控制按钮 */
                cc.find("loading").active = false;
                cc.find("musicLayer").active = true;
                break;
            case "btn1":/* 跳转图鉴界面 */
                GameData.savelocalData(that.fishData);
                GameData.gameUpgrade = 1;
                that.LoadScene("upgrade");

                break;
            case "btn2":/* 跳转升级界面 */

                GameData.savelocalData(that.fishData);
                GameData.gameUpgrade = 2;
                that.LoadScene("upgrade");
                break;
            case "btn3":
                GameData.gameUpgrade = 3;
                GameData.savelocalData(that.fishData);

                that.LoadScene("upgrade");
                break;
            case "playGame":/* 进入游戏 */
                that.LoadScene("game");
                break;

        }
    },
    LoadScene(_scene, type) {
        GameData.stopMusic();
        if (_scene == "game") {
            cc.find("bg").active = true;
            cc.find("bg").opacity = 0;
            cc.find("bg").runAction(
                cc.sequence(
                    cc.fadeIn(1),
                    cc.callFunc(function () {
                        that.loaded = true;
                    })
                )
            );
            cc.director.preloadScene(_scene, function () {
                cc.find("loading").active = false;
            });
        } else {
            cc.director.preloadScene(_scene, function () {
                cc.find("loading").active = false;
                cc.director.loadScene(_scene);
            });
        }
    },
    addcoinAct(x, y, num) {
        var id = GameData.playEffect(this.moveMusic[1]);
        cc.audioEngine.setVolume(id, 1);
        var _coin;
        if (GameData.addcoinAct.size() > 0) {
            _coin = GameData.addcoinAct.get();
        } else {
            _coin = cc.instantiate(this.addcoin);
        }
        _coin.position = cc.v2(x, y);
        _coin.parent = this.node;
        _coin.getComponent("addmoney").init(num);
    },
    start() {

    },
    addqipao() {
        for (var a = 0; a < 10; a++) {
            var _y = Math.floor(Math.random() * 100 - 400);
            var _x = Math.floor(Math.random() * 1136 - 568);
            this.createqipao(_x, _y);
        }
    },
    createqipao(_x, _y) {
        var qipao = cc.instantiate(this.qipao);
        qipao.y = _y;
        qipao.x = _x;
        qipao.parent = this.Layer;
    },
    update(dt) {
        GameData.playTime += dt;
        if (this._t > 0 && GameData.playTime > this._t) {
        // if (GameData.playTime > 5) {
            var num = Math.floor(Math.random() * 100);
            var type;
            if (num <= 80) {
                type = 0
            } else if (num < 95) {
                type = 1
            } else {
                type = 2
            }
            this.initCoin(type);
            GameData.playTime = 0;
        }
        if (this.openShow) {
            this.openShowpanel();
        }
        if (that.loaded) {/*判断主游戏场景中的资源是否加载完成没*/
            that.loaded = false;
            cc.director.loadScene("game");
        }
    },
    onDestroy() {
        GameData.gameHome = null;
    }
});
